package com.ym521.activitystack.core.foreground

import android.app.Application
import androidx.fragment.app.FragmentActivity
import com.ym521.activitystack.core.stack.ActivityStackManager
import com.ym521.activitystack.core.stack.ActivityStackManagerImpl

/**
 *@author Ym
 * @Email 2435970206@qq.com
 * @QQ 2435970206
 * 管理Application的状态 例如是否在前台、后台状态
 * 并且它是ActivityStackMenager的辅助工具，用于对它的增删处理
 */
internal class AppSateManagerImpl private constructor(override val activityStackManager: ActivityStackManager) :
    ActivityLifecycleCallback(), AppSateManager {

    companion object {
        fun builder(): AppSateManager {
            val stackManager = ActivityStackManagerImpl
                .builder()
                .stackClear()
            return AppSateManagerImpl(stackManager)
        }
    }

    override fun registerActivityCallbacks(application: Application): AppSateManagerImpl {
        application.registerActivityLifecycleCallbacks(this)
        return this
    }

    /**
     * APP 当前是否在前台运行
     */
    override fun isForeground(): Boolean {
        return activitySum > 0
    }

    override fun onActivityCreated(activity: FragmentActivity) {
        activityStackManager.push(activity)
    }


    override fun onActivityDestroyed(activity: FragmentActivity) {
        activityStackManager.pop(activity)
    }
}